<?php

class LoginController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        Zend_Loader::loadClass('Zend_Auth');
        $authClass = Zend_Auth::getInstance();

        $auth = $authClass->getStorage()->read();

        if (!$authClass->hasIdentity()) {
            if ($this->_request->isPost()) {
                $data = $this->_request->getPost();

                if ($data['usuario']) {
                    $zendDb = Zend_Db_Table_Abstract::getDefaultAdapter();
                    $authAdapter = new Zend_Auth_Adapter_DbTable(
                                    $zendDb,
                                    'usuario',
                                    'usuario',
                                    'senha',
                                    'MD5(?)'
                    );

                    $authAdapter->setIdentity($data['usuario']);
                    $authAdapter->setCredential($data['senha']);

                    $auth = $authAdapter->authenticate();

                    if ($auth->isValid()) {
                        $authData = $authAdapter->getResultRowObject();

                        $authClass->getStorage()->write(array(
                            'usuario_id' => $authData->idusuario
                        ));

                        return $this->_helper->redirector('index', 'admin');
                    } else {
                        $this->view->priorityMessenger('Login inválido!', 'Mensagem');
                    }
                }
            }
        }

        return $this->_helper->redirector('index', 'index');
    }

    public function logoutAction() {
        Zend_Loader::loadClass('Zend_Auth');
        $authClass = Zend_Auth::getInstance();

        $auth = $authClass->getStorage()->read();

        $authClass->clearIdentity();

        return $this->_helper->redirector('index', 'index');
    }

}

